package com.study.suanfa;

import java.util.LinkedList;

/**
 * @description: LinkedListTest  链表
 * @date: 2020/11/11 20:07
 * @author: hcm
 * @version: 1.0
 */
public class LinkedListTest {

    public static void main(String[] args) throws Exception {

        //实现链表，需要头节点、指针、数据域\
        LinkList linkList = new LinkList();
        linkList.addFirst(1);
        linkList.addFirst(2);
        linkList.addFirst(3);
        linkList.addFirst(4);
        System.out.println(linkList.size());
        System.out.println(linkList.getFirst());
        System.out.println(linkList.getLast());

    }

}

class LinkList{

    //需要一个节点类
    private class Node{
        int data;
        Node next;
    }
    //头指针
    private Node head;

    //尾部指针
    private Node tail;

    //长度
    private int size;

    public int size(){
        return this.size;
    }

    //获取链表中的第一个元素
    public int getFirst() throws  Exception{
        if(this.size == 0){
            throw new Exception("链表为空");
        }
        return this.head.data;
    }

    //获取链表中的最后一个元素
    public int getLast() throws Exception {
        if(this.size == 0){
            throw new Exception("链表为空");
        }
        return this.tail.data;
    }

    //获取链表中的第I个节点的data
    public Node getNodeAt(int index) throws Exception {
        if(this.size == 0){
            throw new Exception("链表为空");
        }
        if(index<0||index >=this.size){
            throw new Exception("错误的下标");
        }
        Node temp = this.head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp;
    }

    //往链表添加元素到最后
    public void  addLast(int data){
        Node node = new Node();
        node.data = data;
        node.next = null;
        if(this.size > 0){
            this.tail.next = node;
        }
        if(this.size == 0){
            this.head = node;
            this.tail = node;
            this.size += 1;
        }
    }

    //添加第一个元素
    public void  addFirst(int data){
        Node node = new Node();
        node.data = data;
        node.next = null;
        if(this.size == 0){
            this.head =node;
            this.tail = node;
            this.size ++ ;
        }else {
            this.head = node;
            this.size++;
        }
    }
}

